Imports ICSharpCode.SharpZipLib.Zip
Imports ICSharpCode.SharpZipLib.GZip
Imports System.IO
Imports System.Net
Imports System.Security.Cryptography
Imports System.Text

Public Class frmLiveUpdate
    Inherits BurtonSoftware.ThemeKit.ThemeForm

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents ProgressBar1 As System.Windows.Forms.ProgressBar
    Friend WithEvents btnInstall As System.Windows.Forms.Button
    Friend WithEvents btnCheckUpdate As System.Windows.Forms.Button
    Friend WithEvents Label1 As System.Windows.Forms.Label

    Friend WithEvents Button1 As System.Windows.Forms.Button
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(frmLiveUpdate))
        Me.ProgressBar1 = New System.Windows.Forms.ProgressBar
        Me.btnInstall = New System.Windows.Forms.Button
        Me.btnCheckUpdate = New System.Windows.Forms.Button
        Me.Label1 = New System.Windows.Forms.Label
        Me.Button1 = New System.Windows.Forms.Button
        Me.SuspendLayout()
        '
        'ProgressBar1
        '
        Me.ProgressBar1.Dock = System.Windows.Forms.DockStyle.Bottom
        Me.ProgressBar1.Location = New System.Drawing.Point(0, 23)
        Me.ProgressBar1.Name = "ProgressBar1"
        Me.ProgressBar1.Size = New System.Drawing.Size(346, 16)
        Me.ProgressBar1.Style = System.Windows.Forms.ProgressBarStyle.Continuous
        Me.ProgressBar1.TabIndex = 8
        '
        'btnInstall
        '
        Me.btnInstall.Enabled = False
        Me.btnInstall.FlatStyle = System.Windows.Forms.FlatStyle.Popup
        Me.btnInstall.Location = New System.Drawing.Point(230, 83)
        Me.btnInstall.Name = "btnInstall"
        Me.btnInstall.Size = New System.Drawing.Size(104, 40)
        Me.btnInstall.TabIndex = 9
        Me.btnInstall.Text = "Download Update"
        Me.btnInstall.Visible = False
        '
        'btnCheckUpdate
        '
        Me.btnCheckUpdate.FlatStyle = System.Windows.Forms.FlatStyle.Popup
        Me.btnCheckUpdate.Location = New System.Drawing.Point(221, 71)
        Me.btnCheckUpdate.Name = "btnCheckUpdate"
        Me.btnCheckUpdate.Size = New System.Drawing.Size(104, 40)
        Me.btnCheckUpdate.TabIndex = 10
        Me.btnCheckUpdate.Text = "Check for Update"
        Me.btnCheckUpdate.Visible = False
        '
        'Label1
        '
        Me.Label1.BackColor = System.Drawing.Color.Transparent
        Me.Label1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
        Me.Label1.Dock = System.Windows.Forms.DockStyle.Bottom
        Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label1.ForeColor = System.Drawing.Color.FromArgb(CType(CType(192, Byte), Integer), CType(CType(0, Byte), Integer), CType(CType(0, Byte), Integer))
        Me.Label1.Location = New System.Drawing.Point(0, 0)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(346, 23)
        Me.Label1.TabIndex = 12
        '
        'Button1
        '
        Me.Button1.FlatStyle = System.Windows.Forms.FlatStyle.Popup
        Me.Button1.Location = New System.Drawing.Point(139, 70)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(104, 40)
        Me.Button1.TabIndex = 14
        Me.Button1.Text = "Close"
        Me.Button1.Visible = False
        '
        'frmLiveUpdate
        '
        Me.AccessibleRole = System.Windows.Forms.AccessibleRole.None
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.BackColor = System.Drawing.Color.FromArgb(CType(CType(224, Byte), Integer), CType(CType(224, Byte), Integer), CType(CType(224, Byte), Integer))
        Me.ClientSize = New System.Drawing.Size(346, 39)
        Me.Controls.Add(Me.Label1)
        Me.Controls.Add(Me.btnCheckUpdate)
        Me.Controls.Add(Me.btnInstall)
        Me.Controls.Add(Me.ProgressBar1)
        Me.Controls.Add(Me.Button1)
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow
        Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
        Me.MaximizeBox = False
        Me.Name = "frmLiveUpdate"
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
        Me.Style = "Vista"
        Me.Text = "Virtual Desk (Live Update)"
        Me.Theme = resources.GetString("$this.Theme")
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private Delegate Sub BarInvoker(ByVal KbCount As Integer)
    Private _oWebClient As WebClient
    Private _oStream As Stream
    Private _oFile As FileStream
    Private _DataBuffer(8191) As Byte
    Private _iTotalBytes As Integer
    Private _iContentLength As Long
    Const sRegKey As String = "SOFTWARE\DIGISYSTEM"
    Private _dLastMod As Date
    Private _sEncryptedFile As String
    Private _sDownloadUrl As String
    Private _dLastUpdateDate As Date
    Private _sInstallPath As String
    Private _sPassword As String
    Private _sEncrypted As String
    Public Function getProcess(ByRef strProcessToKill As String) As Boolean
        Dim proc() As Process = Process.GetProcesses
        For i As Integer = 0 To proc.GetUpperBound(0)
            If proc(i).ProcessName = strProcessToKill Then
                proc(i).Kill()
                Return True
            End If
        Next
        Return False
    End Function

    Private Sub CheckForUpdate()
        'Read Registry
        ReadRegistry()

        If _sDownloadUrl = "" Then
            'Registry could not be read
            Exit Sub
        End If

        'Read at the file info on the server
        Dim oHttpWebRequest As HttpWebRequest
        Dim oHttpWebResponse As HttpWebResponse
        Try
            Me.Update()
            oHttpWebRequest = CType(WebRequest.Create(_sDownloadUrl), HttpWebRequest)
            Me.Update()
            oHttpWebResponse = CType(oHttpWebRequest.GetResponse(), HttpWebResponse)
            Me.Update()
            oHttpWebResponse.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
            Application.Exit()
        End Try

        'Get File Size
        _iContentLength = oHttpWebResponse.ContentLength
        ProgressBar1.Maximum = _iContentLength \ 1024

        'Need to Update?
        _dLastMod = oHttpWebResponse.LastModified
        If _dLastMod = _dLastUpdateDate Then
            ''MsgBox("No new update is available at this time.")
            Application.Exit()
        Else
            If MessageBox.Show("New update is available. Do you whant Install", "Virutal Desk", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = Windows.Forms.DialogResult.Yes Then
                DoDownload()
            Else
                Application.Exit()
            End If

            ''  MsgBox("New update is available: " & _dLastMod)
        End If

        btnInstall.Enabled = True
    End Sub
    Private Sub DoDownload()
        If _dLastMod = _dLastUpdateDate Then
            If MsgBox("No new update is available at this time." & _
                    "  Resinstall current version?", _
                    MsgBoxStyle.YesNo, "Live Update") = MsgBoxResult.No Then
                Exit Sub
            End If
        End If
        If MessageBox.Show("Close Virtual Desk Application Before Press OK.", "Virtual Desk", MessageBoxButtons.OK) = Windows.Forms.DialogResult.OK Then
            If getProcess("VirtualDesk.exe") = True Then
                MessageBox.Show("Close Virtual Desk Application. Before Press OK", "Virtual Desk", MessageBoxButtons.OK)
                Exit Sub
            End If
        End If
        'Begin Download
        btnInstall.Enabled = False
        _iTotalBytes = 0
        Label1.Text = "Downloading..."
        _sEncryptedFile = System.IO.Path.GetTempFileName()
        ''''Application.StartupPath & "\update.zip"
        Download(_sDownloadUrl, _sEncryptedFile)
    End Sub
    Private Sub btnCheckUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheckUpdate.Click
     

    End Sub

    Private Sub btnInstall_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInstall.Click

     
    End Sub

    Sub ContinueInstall()
     
        ''
        'Decrypt if Needed
        Dim sDecryptedFile As String
        If _sEncrypted = "0" Then
            sDecryptedFile = _sEncryptedFile
        Else
            sDecryptedFile = System.IO.Path.GetTempFileName()
            Label1.Text = "Decrypting..."
            System.Windows.Forms.Application.DoEvents()
            DecryptFile(_sPassword, _sEncryptedFile, sDecryptedFile)
        End If

        'Create Temp Folder
        Dim sTempFolder As String = System.IO.Path.GetTempFileName()
        sTempFolder = sTempFolder.Substring(0, sTempFolder.Length - 4)
        If Directory.Exists(sTempFolder) Then
            Directory.Delete(sTempFolder, True)
            Directory.CreateDirectory(sTempFolder)
        Else
            Directory.CreateDirectory(sTempFolder)
        End If

        'Unzip
        Label1.Text = "Decompressing files..."
        Unzip(sDecryptedFile, sTempFolder)

        'Copy and Cleanup
        Try
            MoveFiles(sTempFolder, _sInstallPath)
            MoveFiles(_sInstallPath, Application.StartupPath)
            Label1.Text = "Deleteing temporary files..."
            System.Windows.Forms.Application.DoEvents()
            Dim procinf As New ProcessStartInfo
            procinf.UseShellExecute = False
            procinf.FileName = Application.StartupPath & "\VirtualDesk.exe"
            procinf.WorkingDirectory = Application.StartupPath
            procinf.WindowStyle = ProcessWindowStyle.Normal
            Dim proc As New Process
            proc.StartInfo = procinf
            proc.Start()
            If IO.Directory.Exists(sTempFolder) Then Directory.Delete(sTempFolder, True)
            If IO.File.Exists(sDecryptedFile) Then IO.File.Delete(sDecryptedFile)
            If IO.File.Exists(_sEncryptedFile) Then IO.File.Delete(_sEncryptedFile)
        Catch ex As Exception
            MsgBox(ex.Message)
            Err.Clear()

        End Try

        'Save File Date
        WriteRegistry()

        Label1.Text = ""
        'If MsgBox("Download Complete. Update Ready To Intall", MsgBoxStyle.OKOnly) = MsgBoxResult.OK Then
        '    Dim PROC As New ProcessStartInfo
        '    PROC.FileName = _sInstallPath & "\update.exe"
        '    System.Diagnostics.Process.Start(PROC)
        '    MsgBox("Update is complete!")
        'End If




    End Sub

    Private Sub ReadRegistry()
        Dim oKey As Microsoft.Win32.RegistryKey = _
            Microsoft.Win32.Registry.LocalMachine.OpenSubKey(sRegKey, False)
        If Not oKey Is Nothing Then
            _sDownloadUrl = oKey.GetValue("DownloadUrl")
            _dLastUpdateDate = oKey.GetValue("LastUpdateDate", Now)
            _sInstallPath = oKey.GetValue("InstallPath")
            If Directory.Exists(oKey.GetValue("InstallPath")) = False Then
                Directory.CreateDirectory(oKey.GetValue("InstallPath"))
            End If
            _sPassword = oKey.GetValue("Password")
            _sEncrypted = oKey.GetValue("Encrypted", 1)
            oKey.Close()
        Else
            MessageBox.Show("Invalid Update Information", "Virtual Desk (Live Update)", MessageBoxButtons.OK)
            Application.Exit()
            ''MsgBox("Registry is not set for: HKEY_LOCAL_MACHINE\" & sRegKey & ".", MsgBoxStyle.Critical)
        End If

    End Sub

    Private Sub WriteRegistry()
        Dim oKey As Microsoft.Win32.RegistryKey = _
            Microsoft.Win32.Registry.LocalMachine.OpenSubKey(sRegKey, True)
        If Not oKey Is Nothing Then
            oKey.SetValue("LastUpdateDate", _dLastMod.ToString())
            oKey.SetValue("ContentLength", _iContentLength)
            oKey.Close()
            Application.Exit()
        Else
            MessageBox.Show("Invalid Update Information", "Virtual Desk (Live Update)", MessageBoxButtons.OK)
            Application.Exit()

            ''MsgBox("Registry is not set for: HKEY_LOCAL_MACHINE\" & sRegKey & ".", MsgBoxStyle.Critical)
        End If

    End Sub
    Private Sub CreateRegistry()




    End Sub
    Private Sub Unzip(ByVal sFilePath As String, _
                      ByVal sInstallPath As String)
        If sFilePath = "" Then Exit Sub

        ProgressBar1.Maximum = _iContentLength

        Dim oZipFile As ZipFile = New ZipFile(sFilePath)
        Dim oZipEntry As ZipEntry

        'Unzip each file
        For Each oZipEntry In oZipFile
            If Not oZipEntry.IsDirectory Then
                Dim oStream As Stream = oZipFile.GetInputStream(oZipEntry)
                Dim sTempFilePath As String = sInstallPath & "\" & oZipEntry.Name.ToString.Replace("/", "\")
                MakeFolders(oZipEntry.Name, sInstallPath)
                Dim iFileSize As Long = MakeFile(oStream, sTempFilePath)

                If _iContentLength > ProgressBar1.Value + iFileSize Then
                    ProgressBar1.Value += iFileSize
                End If
                System.Windows.Forms.Application.DoEvents()
            End If
        Next

        oZipFile.Close()
        ProgressBar1.Value = 0
    End Sub

    Private Sub MakeFolders(ByVal sFilePath As String, ByVal sFolderPath As String)
        Dim iPos As Integer = sFilePath.IndexOf("/")
        If iPos = -1 Then Exit Sub

        While (iPos <> -1)
            Dim sFolder As String = sFilePath.Substring(0, iPos)
            iPos = sFilePath.IndexOf("/", iPos + 1)
            Dim sPath As String = sFolderPath & "\" & sFolder.Replace("/", "\")
            If Not Directory.Exists(sPath) Then
                Directory.CreateDirectory(sPath)
            End If
        End While

    End Sub

    Private Function MakeFile(ByRef oStream As Stream, ByVal sTempFilePath As String) As Long
        Dim oFileStream As FileStream = File.OpenWrite(sTempFilePath)
        Dim iSize As Integer = 2048
        Dim iSizeRead As Integer
        Dim oWriteData(2048) As Byte
        Dim iFileSize As Long

        While (True)
            iSizeRead = oStream.Read(oWriteData, 0, iSize)
            If iSizeRead > 0 Then
                oFileStream.Write(oWriteData, 0, iSizeRead)
                iFileSize += iSizeRead
            Else
                Exit While
            End If
        End While

        oFileStream.Close()
        Return iFileSize
    End Function

    Private Sub Download(ByVal sUrl As String, ByVal sFilePath As String)
        'Initialize Download
        _oWebClient = New WebClient
        _oStream = _oWebClient.OpenRead(sUrl)
        _oFile = New FileStream(sFilePath, FileMode.Create)
        _oStream.BeginRead(_DataBuffer, 0, 8192, AddressOf AsynDownload, Nothing)
    End Sub

    Private Sub AsynDownload(ByVal ar As IAsyncResult)
        Dim intCount As Integer
        Try
            intCount = _oStream.EndRead(ar)
            If intCount < 1 Then
                _oStream.Close()
                _oFile.Close()
                _oWebClient.Dispose()
                'MsgBox("Done")
                ProgressBar1.Value = 0
                ContinueInstall()
                Exit Sub
            End If

            _iTotalBytes += intCount
            _oFile.Write(_DataBuffer, 0, intCount)
            Dim params() As Object = {_iTotalBytes}
            Me.Invoke(New BarInvoker(AddressOf Me.DisplayBar), params)
            _oStream.BeginRead(_DataBuffer, 0, 8192, AddressOf AsynDownload, Nothing)

        Catch e As Exception
            MsgBox(e.Message)
        End Try
    End Sub

    Private Sub DisplayBar(ByVal byteCount As Integer)
        If ProgressBar1.Maximum > byteCount \ 1024 Then
            ProgressBar1.Value = byteCount \ 1024
        End If
    End Sub

    Private Sub DecryptFile(ByVal sPassword As String, _
                        ByVal sOldFilePath As String, _
                        ByVal sNewFilePath As String)
        Try
            Dim sKey As Byte() = (New UnicodeEncoding).GetBytes(sPassword.PadRight(8, "*"))
            Dim oOldFileStream As New FileStream(sOldFilePath, FileMode.Open)
            Dim oNewFileStream As New FileStream(sNewFilePath, FileMode.Create)
            Dim oRijndaelManaged As New RijndaelManaged
            Dim oCryptoStream As New CryptoStream(oOldFileStream, _
                oRijndaelManaged.CreateDecryptor(sKey, sKey), CryptoStreamMode.Read)
            Dim data As Integer

            While True
                data = oCryptoStream.ReadByte()
                If data = -1 Then Exit While
                oNewFileStream.WriteByte(CByte(data))
            End While

            oNewFileStream.Close()
            oCryptoStream.Close()
            oOldFileStream.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub

    Private Sub MoveFiles(ByVal sSourcePath As String, _
                          ByVal sDestinationPath As String)
        ProgressBar1.Value = 0
        If Not System.IO.Directory.Exists(sDestinationPath) Then
            System.IO.Directory.CreateDirectory(sDestinationPath)
        End If

        Label1.Text = "Copying files..."
        System.Windows.Forms.Application.DoEvents()
        Dim oFiles() As String = System.IO.Directory.GetFiles(sSourcePath)
        ProgressBar1.Maximum = oFiles.Length
        For i As Integer = 0 To oFiles.Length - 1
            System.IO.File.Copy(oFiles(i), _
                sDestinationPath & "\" & IO.Path.GetFileName(oFiles(i)), True)
            ProgressBar1.Value = i
        Next

        Label1.Text = "Copying folders..."
        System.Windows.Forms.Application.DoEvents()
        Dim oFolders() As String = System.IO.Directory.GetDirectories(sSourcePath)
        ProgressBar1.Maximum = oFolders.Length
        For i As Integer = 0 To oFolders.Length - 1
            Dim sPath As String = oFolders(i).Substring(sSourcePath.Length)

            If System.IO.Directory.Exists(sDestinationPath & sPath) Then
                System.IO.Directory.Delete(sDestinationPath & sPath, True)
            End If

            System.IO.Directory.Move(oFolders(i), _
                sDestinationPath & sPath)
            ProgressBar1.Value = i
        Next

        ProgressBar1.Value = 0
    End Sub

    Private Sub frmLiveUpdate_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        CheckForUpdate()
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Me.Close()
    End Sub
End Class
